package org.practice.action;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HttpSession session = request.getSession();
		// ������Ӧ����
		response.setContentType("image/jpeg");
		// ͼƬ���ڴ�ӳ�񣬱���ͼƬ��������Ϣ
		BufferedImage image = new BufferedImage(60, 20,
				BufferedImage.TYPE_INT_RGB);
		// ��û��ʶ���
		Random r = new Random();
		Graphics g = image.getGraphics();
		g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
		g.fillRect(0, 0, 60, 20);
		g.setColor(new Color(0,0,0));
		String number = String.valueOf(r.nextInt(99999)); 
		//�������number���浽HttpSession�����У��Ա��������֤�û�ע����д����֤��
		session.setAttribute("number", number);
		
		g.drawString(number, 5, 15);
		//���response������ֽ����������
		OutputStream os = response.getOutputStream();
		// ѹ����jpeg��ʽ
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

		// ��BufferedImage�����е�ͼ����Ϣ�����,��������encoder����ʱָ������������
		encoder.encode(image);

		return null;
	}
	
}
